package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService service;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    //新增菜品
    //dto：前段传递的复杂的数据分装
    //vo:后端复杂的数据，返回给前端的封装
    @PostMapping
    @CacheEvict(value = "dish", key = "#dishDto.categoryId")
    public R saveDish(@RequestBody DishDto dishDto) {

        //保存菜品数据到dish表
        service.save(dishDto);

        //保存口味数据到dish_flavor表
        List<DishFlavor> flavors = dishDto.getFlavors();
    /*  //for循环方法
        for (DishFlavor flavor : flavors) {
            //设置口味对应的菜品的id
            flavor.setDishId(dishDto.getId());
        } */
        //lambda表达式方法
        flavors = flavors.stream().map((flavor) -> {
            flavor.setDishId(dishDto.getId());
            return flavor;
        }).collect(Collectors.toList());
        //insert into dish_flavor values ('','',...),(),()...
        dishFlavorService.saveBatch(flavors);
        /*//清理缓存
        String key = "dish_" + dishDto.getCategoryId() ;
        redisTemplate.delete(key);*/
        return R.success("新增菜品成功");
    }

    @GetMapping("/page")
    public R pageQuery(int page, int pageSize, String name) {

        //进行分页查询
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.like(name != null, Dish::getName, name);
        qw.orderByDesc(Dish::getUpdateTime);
        service.page(pageInfo, qw);
        long total = pageInfo.getTotal();
        List<Dish> records = pageInfo.getRecords();
        Map map = new HashMap();
        map.put("total", (int) total);

      /*  //for循环
        List<DishDto> list = new ArrayList<DishDto>();
        for (Dish record : records) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(record,dishDto);
            Long categoryId = record.getCategoryId();
            Category byId = categoryService.getById(categoryId);
            if(byId!=null){
                dishDto.setCategoryName(byId.getName());
            }
            list.add(dishDto);
        }*/
        //lambada表达式
        List<DishDto> list = records.stream().map((record) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(record, dishDto);
            Long categoryId = record.getCategoryId();
            Category byId = categoryService.getById(categoryId);
            if (byId != null) {
                dishDto.setCategoryName(byId.getName());
            }
            return dishDto;
        }).collect(Collectors.toList());
        map.put("records", list);
        return R.success(map);
    }

    @GetMapping("/{id}")
    public R getByIdQuery(@PathVariable Long id) {
        //查询菜品基本信息，从dish 表中查询
        Dish dish = service.getById(id);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);
        //查询当前菜品对应的口味信息，从dish_flavor 表查询
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId, id);
        List<DishFlavor> flavors = dishFlavorService.list(wrapper);
        dishDto.setFlavors(flavors);
        return R.success(dishDto);
    }

    @PutMapping
    @CacheEvict(value = "dish",allEntries = true) //清除所有缓存
    public R updateDishAndFlavor(@RequestBody DishDto dishDto) {
        //更新dish 表基本信息
        service.updateById(dishDto);
        //清理当前菜品对应口味数据 -- dish_flavor 表的 delete操作
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(wrapper);
        //添加当前菜品提交过来口味数据--dish_flavor 表的insert操作
        List<DishFlavor> flavors = dishDto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
        }
        /*flavors = flavors.stream().map((flavor) -> {
            flavor.setDishId(dishDto.getId());
            return flavor;
        }).collect(Collectors.toList());*/
        dishFlavorService.saveBatch(flavors);
      /*
        //清理缓存
        String key = "dish_" + dishDto.getCategoryId() ;
        redisTemplate.delete(key);*/
        return R.success("修改菜品成功");
    }

    @DeleteMapping
    @CacheEvict(value = "dish",allEntries = true) //清除所有缓存
    public R deleteDishes(@RequestParam List<Long> ids) {
        //先删除菜品对应的口味
        LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
        qw.in(DishFlavor::getDishId, ids);
        dishFlavorService.remove(qw);
        //在删除菜品
        service.removeByIds(ids);

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Dish::getId, ids);
      /*  List<Dish> list = service.list(queryWrapper);
        for (Dish dish : list) {
            //清理缓存
            String key = "dish_"+dish.getCategoryId();
            redisTemplate.delete(key);
        }*/
        return R.success("删除成功");
    }

    @PostMapping("/status/{status}")
    @CacheEvict(value = "dish",allEntries = true)
    public R updateDishStatus(@PathVariable Integer status, @RequestParam List<Long> ids) {
     /*   QueryWrapper wrapper = new QueryWrapper();
        wrapper.in("id",ids);
        Dish dish = new Dish();
        dish.setStatus(status);
        service.update(dish,wrapper);
        */

        LambdaUpdateWrapper<Dish> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(Dish::getStatus, status);
        wrapper.in(Dish::getId, ids);
        service.update(wrapper);

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Dish::getId, ids);
        List<Dish> list = service.list(queryWrapper);
        /*for (Dish dish : list) {
            //清理缓存
            String key = "dish_"+dish.getCategoryId();
            redisTemplate.delete(key);
        }*/

        return R.success("操作成功");
    }

    //根据分类id查询该分类下的所有菜品集合
    @GetMapping("/list")
    @Cacheable(value = "dish",key = "#categoryId")
    public R list(Long categoryId, Integer status) {
        //动态设置key
        String key = "dish_" + categoryId ;
        List<DishDto> dishDtosInRedis = null;
/*
        //先从redis中获取缓存数据
        dishDtosInRedis = (List<DishDto>) redisTemplate.opsForValue().get(key);*/

        //如果存在，直接返回，无需查询数据库
        if (dishDtosInRedis != null) {
            return R.success(dishDtosInRedis);
        }

        //如果不存在，则查询数据库
        LambdaQueryWrapper<Dish> wq = new LambdaQueryWrapper<>();
        wq.eq(Dish::getCategoryId, categoryId);
        wq.eq(Dish::getStatus, status);

        List<Dish> list = service.list(wq);
        List<DishDto> dishDtos = new ArrayList<>();
      /*  //for循环
        for (Dish dish : list) {
            DishDto dishDto = new DishDto();
            //菜品数据
            BeanUtils.copyProperties(dish, dishDto);
            //菜品口味数据
            LambdaUpdateWrapper<DishFlavor> qw1 = new LambdaUpdateWrapper<>();
            qw1.eq(DishFlavor::getDishId, dish.getId());
            List<DishFlavor> list1 = dishFlavorService.list(qw1);
            dishDto.setFlavors(list1);
            dishDtos.add(dishDto);
        }*/
        //lambda表达式
        dishDtos = list.stream().map((dish) -> {
            DishDto dishDto = new DishDto();
            //菜品数据
            BeanUtils.copyProperties(dish, dishDto);
            //菜品口味数据
            LambdaUpdateWrapper<DishFlavor> qw1 = new LambdaUpdateWrapper<>();
            qw1.eq(DishFlavor::getDishId, dish.getId());
            List<DishFlavor> list1 = dishFlavorService.list(qw1);
            dishDto.setFlavors(list1);
            return dishDto;
        }).collect(Collectors.toList());

       /* //把数据存入redis
        redisTemplate.opsForValue().set(key, dishDtos, 30, TimeUnit.MINUTES);*/
        return R.success(dishDtos);
    }
}
